package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.dto.RoleDTO;
import com.itheima.dto.UserDTO;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.config.authentication.UserServiceBeanDefinitionParser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author: bowen
 * @Date: 2019/7/22 15:05
 * @Description:
 */
@Component
public class HealthUserService implements UserDetailsService {

	@Reference
	UserService userService;


	/**
	 *  @描述：根据用户查询用户信息（基本信息，权限信息），返回给框架
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 查询用户信息（基本信息，角色信息，权限信息）
		UserDTO user = userService.findByUsername(username);
		if(ObjectUtils.isEmpty(user)){
		    return null;
		}

		// 生成权限列表
		Set<RoleDTO> roles = user.getRoles();
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		if(!CollectionUtils.isEmpty(roles)){
            roles.forEach(role->{
	            Set<Permission> permissions = role.getPermissions();
	            permissions.forEach(permission -> {
		            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
	            });

            });
		}


		return new org.springframework.security.core.userdetails.User(username,
				user.getPassword(),
				grantedAuthorities);
	}
}
